const express = require('express')
const router = express.Router()
const userDB = require('../../db/user')
const tempPwDB = require('../../db/temppw')

// 重置密码
router.post('/', async (req, res) => {
  let {user, pass, rpkey} = req.body
  let reg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/
  
  if(!reg.test(pass)){
    return res.send({
      code: 1,
      msg: '密码格式不正确'
    })
  }
  
  let doc = await userDB.findOne({user})
  if(!doc){
    return res.send({
      code: 2,
      msg: '此账号未注册'
    })
  }
  
  // 修改密码
  await userDB.updateOne({user}, {pass})
    
  //删除临时key
  await tempPwDB
            .deleteOne({_id: rpkey})
            .catch(err=>{
                    if(err) throw err
                  })
  
  // 清除session
  req.session.destroy()
  
  // 返回前端
  res.send({
    code: 0,
    msg: '密码重置成功'
  })
})

// 检查key是否存在，不存在则为无效key
router.post('/check', async (req, res) => {
  let {key} = req.body
  let doc = await tempPwDB.findOne({_id: key})
  if(!doc){
    return res.send({
      code: 1,
      msg: 'invalidkey'
    })
  }

  res.send({
    code: 0,
    msg: 'activekey'
  })
})
module.exports = router